<template>
  <div class="login">
    <div>
      <el-input
        placeholder="请输入用户名"
        v-model="username"
        clearable
        class="input_style"
      ></el-input>
    </div>
    <div>
      <el-input
        placeholder="请输入密码"
        v-model="password"
        show-password
        class="input_style"
      ></el-input>
    </div>
    <div>
      <el-button type="primary" @click="login" class="login_style"
        >登录</el-button
      >
    </div>
  </div>
</template>

<script>
import request from "../request";
import qs from "qs";//导入qs库
export default {
  name: "login",
  //文件里面用到的数据
  data() {
    return {
      username: "",
      password: "",
    };
  },
  methods: {
    login() {
      if (this.username == "" || this.password == "") {
        this.$message.error("请输入账号密码");
        return;
      }
      const data = { username: this.username, password: this.password };
      request({
        url: "/login/",
        method: "post",
        data: qs.stringify(data),//转换格式
      })
        .then((res) => {
          if (res.code == 200) {
            this.$message.success("登录成功！");
            this.$router.push({
              name: "home",
            });
            sessionStorage.setItem("userinfo", JSON.stringify(res.data));
            sessionStorage.setItem("login_status", true);
          } else {
            this.$message.error(res.message); //状态码非200的错误
          }
        })
        .catch((err) => {  //请求失败的错误,如后端没有启动
          this.$message.error(err.message);
        });
    },
  },
};
</script>

<style>
.login {
    width: 260px;
    margin: auto;
    margin-top: 200px;
}
.input_style {
  margin-bottom: 10px;
}
.login_style {
  width: 260px;
}
</style>
